// pages/lifePay/queryPrice/queryPrice.js
var Ajax = require('../../../utils/Ajax.js')
var utils = require('../../../utils/util.js');
var config = require('../../../base.conf.js').config;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSend: false,
    number: '',
    steps: 1,
    lifeBillQuery:'',
    options: {
      type: 1
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    this.setData({
      options
    }, () => {
      if (options.type == 0) {
        wx.setNavigationBarTitle({
          title: '水费'
        })
      } else if (options.type == 1) {
        wx.setNavigationBarTitle({
          title: '电费'
        })
      } else if (options.type == 2) {
        wx.setNavigationBarTitle({
          title: '燃气费'
        })
      }
    })
  },
  //返回上一页重新选择
  selectCompany() {
    wx.navigateBack()
  },
  toPage(){
    utils.toPage('/pages/paycost/paycost')
  },
  oninput(e) { //获取输入的值
    var {
      name
    } = e.currentTarget.dataset;
    var {
      value
    } = e.detail;
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“/\"'。\\，、_？\\s+]")
    this.setData({
      [name]: value.replace(pattern, "")
    })
  },
  addZero(numbers) { //小于10前面加一个零
    if (numbers < 10 && numbers != 0) {
      return "0" + numbers
    }
    return numbers;
  },
  //获取上一月
  getPreMonth(flag=true) {
    var date = utils.formatTime(new Date());
    date = date.replace(/\//g, '-')
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
      year2 = parseInt(year2) - 1;
      month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
      day2 = days2;
    }
    if (month2 < 10) {
      month2 = '0' + month2;
    }
    var t2 =month2;
    if (flag){
      t2 = year2 + '' + month2
    }
    return t2;
  },
  //查询账单
  checkOrder() {
    var that = this
    var {
      options,
      number,
    } = this.data
    utils.showLoading('正在查询');
    Ajax.post('lifeBillQuery', {
      productId: options.productNumber,
      account: number,
      yearMonth: this.getPreMonth(),
      userId: app.getValueSync("openid")
    }, {
      "content-type": "application/json;charset=UTF-8",
    }).then((d) => {
      utils.hideLoading();
      if (d.status == 200&&d.data) {
        d.data.month = this.getPreMonth(false); 
        console.log(JSON.stringify(d.data))
        var steps = d.data.totalamount >0 ? 2:3
        this.setData({
          lifeBillQuery: d.data,
          steps,
        })
      } else {
        if (d&& d.msg=="暂未查询到欠费"){
          this.setData({
            steps:3,
          })
        }else{
          utils.showtoast(d.msg || d.message || d.failmessage || '服务器错误')
        }
      }
    }).catch((e) => {
      utils.hideLoading();
      console.log(e)
      utils.showtoast('网络错误')
    })
  },
  topev(e){
    var { steps, number}=this.data;
    var { first}=e.currentTarget.dataset;
     this.setData({
       lifeBillQuery:'',
       number: first == 1 ? '' : number,
       steps:1,
     })
  },
  //缴费
  payFn() {
    var that = this
    var {
      options,
      number,
      lifeBillQuery
    } = this.data
    var list = lifeBillQuery.wecbilldata||[];
    var delayfee = 0;
    list.map((item)=>{//循环滞纳金
      delayfee +=item.delayfee||0
    })
    Ajax.post('wxUnifiedOrder', {
      productId: options.productNumber,
      account: number,
      type:options.type,
      money:lifeBillQuery.totalamount||0,
      delayfee,
      userId: app.getValueSync("openid")
    }, {
      "content-type": "application/json;charset=UTF-8",
    }).then((d) => {
      if (d.status == 200&&d.data) {
        this.playorder(d.data);  
      } else {
        utils.showtoast(d.msg || d.message || d.failmessage || '服务器错误')
      }
    }).catch((e) => {
      console.log(e)
      utils.showtoast('网络错误')
    })
  },
  playorder(obj){
    wx.requestPayment({
      timeStamp: obj.timeStamp,
      nonceStr: obj.nonceStr,
      package: obj.package,
      signType: obj.signType,
      paySign: obj.paySign,
      success: (res)=> {
        this.setData({
          steps:3
        })
      },
      fail: function (res) {
        if (res.errMsg.indexOf("cancel") != -1) {
          utils.showtoast('已取消微信支付')
        } else {
          console.log(res)
          utils.showtoast('发起微信支付失败')
        }

      }
    }) 
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})